import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_aygsh/entity/address_entity.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/util/AppSaveInfoUtil.dart';
import '../../base/Constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../util/SignUtil.dart';
import '../../event/AddrEvent.dart';
import '../../base/application.dart';
import '../../util/Toast.dart';
/**
 * 添加收货地址
 * 2019-8-27
 */
class AddAddressPage extends StatefulWidget {
  AddressListDataData item;
  AddAddressPage({Key key, this.item}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new AddAddressView();
  }
}

class AddAddressView extends State<AddAddressPage> {
  String address = "选择地区";
  String token = "";
  bool _value = false;
  String name = "";
  String phone = "";
  String detail_address = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.item != null) {
      setState(() {
        address = widget.item.province +
            "-" +
            widget.item.city +
            "-" +
            widget.item.county;
        name = (widget.item.consignee == null ? "" : widget.item.consignee);
        phone = widget.item.contact_number;
        detail_address = widget.item.detail_address;
        _value = (widget.item.is_default == "Y");
      });
    }
    getString(TOKEN).then((value) {
      token = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: new AppBar(
        title: new Text(
          widget.item != null ? "编辑地址" : "添加地址",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.2,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: new Container(
        child: new Column(
          children: <Widget>[
            initName(),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            initPhone(),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            initAddress(context),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            initDetail(),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            addButton(context)
          ],
        ),
      ),
    );
  }

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return null;
  }

  Widget initName() {
    return new Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '收货人:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new TextField(
                maxLines: 1,
                cursorColor: mainColor,
                onChanged: (value) {
                  name = value;
                },
                keyboardAppearance: Brightness.light,
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: name == null ? "" : name,
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: name == null ? 0 : name.length)))),
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                decoration: new InputDecoration(
                    hintText: "",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
        ],
      ),
    );
  }

  Widget initPhone() {
    return new Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '联系方式:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new TextField(
                maxLines: 1,
                cursorColor: mainColor,
                onChanged: (value) {
                  phone = value;
                },
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: phone,
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: phone.length)))),
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                decoration: new InputDecoration(
                    hintText: "",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
        ],
      ),
    );
  }

  Widget initDetail() {
    return Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '详细地址:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new TextField(
                maxLines: 2,
                cursorColor: mainColor,
                minLines: 2,
                keyboardAppearance: Brightness.light,
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: detail_address,
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: detail_address.length)))),
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                onChanged: (value) {
                  detail_address = value;
                },
                decoration: new InputDecoration(
                    hintText: "输入详细街道、楼栋号等",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
        ],
      ),
    );
  }

  Widget addButton(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      height: 40,
      margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
      decoration: new BoxDecoration(
        color:Color.fromARGB(255, 255, 140, 16),
          borderRadius: BorderRadius.circular(20.0)),
      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
      child: new FlatButton(
        child: new Padding(
          padding: EdgeInsets.all(0.0),
          child: new Text(
            widget.item != null ? "修改地址" : "确定添加",
            style: new TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          ),
        ),
        onPressed: () {
          addAddress();
        },
      ),
    );
  }

  Widget initAddress(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '收货地区:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new GestureDetector(
                onTap: () {
                  showAddressDialog(context);
                },
                child: new Container(
                  padding: EdgeInsets.fromLTRB(0, 15.0, 0, 15.0),
                  child: new Row(
                    children: <Widget>[
                      Expanded(
                        child: new Text(
                          '$address',
                          style: TextStyle(
                              color: address.contains("选择")
                                  ? Colors.black45
                                  : Colors.black87,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.grey,
                        size: 18,
                      )
                    ],
                  ),
                ),
              )),
        ],
      ),
    );
  }

  Future showAddressDialog(BuildContext context) async {
    Result result = await CityPickers.showCityPicker(
      context: context,
    );
    if (result == null) {
      return;
    }
    setState(() {
      address =
          result.provinceName + "-" + result.cityName + "-" + result.areaName;
    });
  }

  addAddress() async {
    if (name == "") {
      Toast.toast(context,msg: "请输入收货人");
      // Fluttertoast.showToast(msg: "请输入收货人");
      return;
    }
    if (phone == "") {
      // Fluttertoast.showToast(msg: "请输入收件人号码");
      Toast.toast(context,msg: "请输入收件人号码");
      return;
    }
    if (address == "") {
      // Fluttertoast.showToast(msg: "请选择收货地区");
      Toast.toast(context,msg: "请选择收货地区");
      return;
    }
    if (detail_address == "") {
      // Fluttertoast.showToast(msg: "请输入详细街道地址");
      Toast.toast(context,msg: "请输入详细街道地址");
      return;
    }
    if (widget.item != null) {
      Map map = new Map.from({
        "sign_type": createSignType(Api.URL_ADDRESS_EDIT),
        "token": token,
        "address_id": widget.item.id,
        "province": address.split("-")[0],
        "city": address.split("-")[1],
        "county": address.split("-")[2],
        "detail_address": detail_address,
        "consignee": name,
        "contact_number": phone,
        "is_default": _value ? "Y" : "N"
      });
      Response<String> response =
          await HttpUtil().post(Api.URL_ADDRESS_EDIT, data: getSign(map));
      Map userMap = json.decode(response.data);
      int code = userMap["code"];
      String msg = userMap["msg"];

      // Fluttertoast.showToast(msg: msg);
      Toast.toast(context,msg:msg);
      // print(userMap['data'].toString());
      if (code == 1) {
        APPLIC.eventBus.fire(AddrEvent());
        Navigator.of(context).pop();
      }
      return;
    }
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_ADDRESS_ADD),
      "token": token,
      "province": address.split("-")[0],
      "city": address.split("-")[1],
      "county": address.split("-")[2],
      "detail_address": detail_address,
      "consignee": name,
      "contact_number": phone,
      "is_default": _value ? "Y" : "N"
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_ADDRESS_ADD, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
Toast.toast(context,msg:msg);
    // Fluttertoast.showToast(msg: msg);
    // print(userMap['data'].toString());
    if (code == 1) {
      APPLIC.eventBus.fire(AddrEvent());
      Navigator.of(context).pop();
    }
  }
}
